package com.ruyuan.payment.server.service;

import com.ruyuan.payment.server.domain.Member;
import com.ruyuan.payment.server.domain.MemberExample;
import com.ruyuan.payment.server.exception.BusinessException;
import com.ruyuan.payment.server.exception.BusinessExceptionEnum;
import com.ruyuan.payment.server.mapper.MemberMapper;
import com.ruyuan.payment.server.req.MemberLoginReq;
import com.ruyuan.payment.server.req.MemberRegisterReq;
import com.ruyuan.payment.server.resp.MemberLoginResp;
import com.ruyuan.payment.server.util.CopyUtil;
import com.ruyuan.payment.server.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class MemberService {
    private static final Logger LOG = LoggerFactory.getLogger(MemberService.class);

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private AccountService accountService;

    @Transactional
    public void register(MemberRegisterReq req) {
        // 增加登录名重复校验
        String loginName = req.getLoginName();
        MemberExample memberExample = new MemberExample();
        memberExample.createCriteria().andLoginNameEqualTo(loginName);
        List<Member> list = memberMapper.selectByExample(memberExample);
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException(BusinessExceptionEnum.MEMBER_LOGIN_NAME_EXIST);
        }

        Member member = CopyUtil.copy(req, Member.class);
        member.setId(snowFlake.nextId());
        member.setRegisterTime(new Date());
        memberMapper.insert(member);

        LOG.info("创建账户开始");
        accountService.add(member.getId());
    }

    public MemberLoginResp login(MemberLoginReq req) {
        // 校验登录名是否存在
        String loginName = req.getLoginName();
        MemberExample memberExample = new MemberExample();
        memberExample.createCriteria().andLoginNameEqualTo(loginName);
        List<Member> list = memberMapper.selectByExample(memberExample);
        if (CollectionUtils.isEmpty(list)) {
            LOG.info("登录名不存在，登录名：{}", loginName);
            throw new BusinessException(BusinessExceptionEnum.MEMBER_LOGIN_ERROR);
        }
        Member member = list.get(0);

        // 校验密码
        if (req.getPassword().equals(member.getPassword())) {
            // 登录成功
            return CopyUtil.copy(member, MemberLoginResp.class);
        } else {
            // 登录失败
            LOG.info("密码错误，登录名：{}", loginName);
            throw new BusinessException(BusinessExceptionEnum.MEMBER_LOGIN_ERROR);
        }

    }

}
